package cn.tedu.zhyl.base.oss;

import cn.hutool.core.date.DateUtil;
import cn.tedu.zhyl.base.exception.ServiceException;
import cn.tedu.zhyl.base.properties.MinioProperties;
import cn.tedu.zhyl.base.response.StatusCode;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Component
public class MinioUpload {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    public String fileUpload(MultipartFile file) {
        String url = null;

        try {
            // 判断数据存储桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }


            // 创建文件夹
            String pathDir = DateUtil.format(new Date(), "yyyyMMdd");
            // 随机uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 组成文件名称
            String fileName = pathDir+"/"+uuid+file.getOriginalFilename();

            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());


            // 拼接上传后的文件路径
            url = minioProperties.getEndPointUrl()+"/"+minioProperties.getBucketName()+"/"+fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return url;
    }
    public void deleteFile(String fileName){
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(StatusCode.FILE_DELETED_ERROR);
        }
    }
}
